package com.ningxun.pagentcrawler.service.core.impl;

import com.ningxun.pagent.common.core.domain.model.LoginUser;
import com.ningxun.pagent.common.utils.SecurityUtils;
import com.ningxun.pagentcrawler.entity.policy.PolicyItem;
import com.ningxun.pagentcrawler.dto.CrawlerResult;
import com.ningxun.pagentcrawler.service.policy.IPolicyTypeService;
import com.ningxun.pagentcrawler.service.policy.IPolicyConverterService;
import com.ningxun.pagent.bus.domain.BusPolicyContent;
import com.ningxun.pagent.bus.service.IBusPolicyContentService;
import com.ningxun.pagentcrawler.service.core.ICrawlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.ningxun.pagent.flow.constant.FlowConstant.FLOW_NAME;

/**
 * 爬虫服务实现类
 * 负责爬虫业务逻辑处理
 * 
 * @author pagent
 * @date 2025-01-XX
 */
@Service
public class CrawlerServiceImpl implements ICrawlerService {

    @Autowired
    private IBusPolicyContentService busPolicyContentService;
    
    @Autowired
    private IPolicyTypeService policyTypeService;
    
    @Autowired
    private IPolicyConverterService policyConverterService;

    /**
     * 保存政策数据到数据库
     */
    @Override
    public boolean savePolicyToDatabase(PolicyItem policyItem) {
        try {
            // 构建去重检查标题
            String fullTitleForCheck = policyConverterService.buildDuplicateCheckTitle(policyItem);
            System.out.println("🔍 构建去重检查标题: " + fullTitleForCheck);
            
            // 检查是否已存在相同完整标题的政策
            BusPolicyContent existingPolicyQuery = new BusPolicyContent();
            existingPolicyQuery.setTitle(fullTitleForCheck);
            List<BusPolicyContent> existingPolicies = busPolicyContentService.selectBusPolicyContentList(existingPolicyQuery);
            
            if (!existingPolicies.isEmpty()) {
                // 找到相同去重检查标题的政策，直接跳过
                System.out.println("⚠️ 跳过重复政策: " + policyItem.getTitle());
                System.out.println("   - 原因: 去重检查标题已存在");
                System.out.println("   - 去重检查标题: " + fullTitleForCheck);
                return false;
            }
            
            // 根据标题自动设置政策类型
            Long policyType = policyTypeService.determinePolicyType(policyItem.getTitle());
            
            // 转换数据
            BusPolicyContent busPolicyContent = policyConverterService.convertToBusPolicyContent(policyItem, policyType);

            // 调用服务保存到数据库
            int result = busPolicyContentService.insertBusPolicyContent(busPolicyContent);
            //加入工作流

            
            if (result > 0) {
                System.out.println("✅ 政策已成功保存到数据库: " + policyItem.getTitle() + 
                                 " (类型: " + policyTypeService.getPolicyTypeName(policyType) + ")");
                return true;
            } else {
                System.err.println("❌ 保存政策到数据库失败: " + policyItem.getTitle());
                return false;
            }
            
        } catch (Exception e) {
            System.err.println("保存政策到数据库异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 批量保存政策数据
     */
    @Override
    public CrawlerResult savePoliciesToDatabase(List<PolicyItem> policies) {
        System.out.println("开始保存政策数据到数据库...");
        
        if (policies.isEmpty()) {
            System.out.println("⚠️ 没有爬取到任何数据");
            return new CrawlerResult(0, 0, "没有数据需要保存");
        }

        int successCount = 0;
        int failCount = 0;
        int skipCount = 0;  // 统计跳过的数量

        //遍历每一条爬到的政策 进入工作流
        for (PolicyItem policyItem : policies) {
            try {
                boolean success = savePolicyToDatabase(policyItem);
                if (success) {
                    successCount++;
                } else {
                    failCount++;
                    skipCount++; // 记录跳过的政策
                }
            } catch (Exception e) {
                System.err.println("保存政策失败: " + policyItem.getTitle() + " - " + e.getMessage());
                System.err.println("   - 错误类型: " + e.getClass().getSimpleName());
                System.err.println("   - 错误详情: " + e.getStackTrace()[0]);
                failCount++;
            }
        }
        
        System.out.println("✅ 数据库保存完成！");
        System.out.println("   - 成功新增: " + successCount + " 条");
        System.out.println("   - 跳过重复: " + skipCount + " 条");
        System.out.println("   - 保存失败: " + (failCount - skipCount) + " 条");
        System.out.println("   - 总计处理: " + policies.size() + " 条");
        
        return new CrawlerResult(successCount, failCount, "保存完成");
    }
} 